import React, { useState, useRef } from 'react';
import { Download, Maximize2, Minimize2, Palette, Settings, Calendar, BarChart3, PieChart, TrendingUp } from 'lucide-react';
import { useChartContext } from '../../contexts/ChartContext';
import { toPng, toSvg } from 'html-to-image';

interface ChartCustomizationProps {
  className?: string;
}

type ChartTheme = 'default' | 'dark' | 'colorful' | 'minimal' | 'nature';
type ExportFormat = 'png' | 'svg' | 'pdf';
type DateRange = '7d' | '30d' | '90d' | '1y' | 'all';

interface ThemeConfig {
  name: string;
  colors: {
    primary: string;
    secondary: string;
    accent: string;
    background: string;
    text: string;
    grid: string;
  };
  chartColors: string[];
}

const themes: Record<ChartTheme, ThemeConfig> = {
  default: {
    name: 'Default',
    colors: {
      primary: '#3b82f6',
      secondary: '#10b981',
      accent: '#f59e0b',
      background: '#ffffff',
      text: '#374151',
      grid: '#f3f4f6'
    },
    chartColors: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#06b6d4', '#84cc16']
  },
  dark: {
    name: 'Dark',
    colors: {
      primary: '#60a5fa',
      secondary: '#34d399',
      accent: '#fbbf24',
      background: '#1f2937',
      text: '#f9fafb',
      grid: '#374151'
    },
    chartColors: ['#60a5fa', '#34d399', '#fbbf24', '#f87171', '#a78bfa', '#22d3ee', '#a3e635']
  },
  colorful: {
    name: 'Colorful',
    colors: {
      primary: '#ec4899',
      secondary: '#06b6d4',
      accent: '#f59e0b',
      background: '#ffffff',
      text: '#1f2937',
      grid: '#f3f4f6'
    },
    chartColors: ['#ec4899', '#06b6d4', '#f59e0b', '#ef4444', '#8b5cf6', '#10b981', '#f97316']
  },
  minimal: {
    name: 'Minimal',
    colors: {
      primary: '#6b7280',
      secondary: '#9ca3af',
      accent: '#374151',
      background: '#ffffff',
      text: '#111827',
      grid: '#f9fafb'
    },
    chartColors: ['#6b7280', '#9ca3af', '#d1d5db', '#374151', '#4b5563', '#111827', '#f3f4f6']
  },
  nature: {
    name: 'Nature',
    colors: {
      primary: '#059669',
      secondary: '#0d9488',
      accent: '#ca8a04',
      background: '#f0fdf4',
      text: '#14532d',
      grid: '#dcfce7'
    },
    chartColors: ['#059669', '#0d9488', '#ca8a04', '#dc2626', '#7c3aed', '#0891b2', '#65a30d']
  }
};

const ChartCustomization: React.FC<ChartCustomizationProps> = ({ className = '' }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [currentTheme, setCurrentTheme] = useState<ChartTheme>('default');
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [selectedDateRange, setSelectedDateRange] = useState<DateRange>('30d');
  const [isExporting, setIsExporting] = useState(false);
  
  const { filters, setFilters, clearFilters } = useChartContext();
  const chartContainerRef = useRef<HTMLDivElement>(null);
  
  const handleThemeChange = (theme: ChartTheme) => {
    setCurrentTheme(theme);
    // Apply theme to CSS variables
    const root = document.documentElement;
    const themeConfig = themes[theme];
    
    Object.entries(themeConfig.colors).forEach(([key, value]) => {
      root.style.setProperty(`--chart-${key}`, value);
    });
    
    // Store theme preference
    localStorage.setItem('chart-theme', theme);
  };
  
  const handleDateRangeChange = (range: DateRange) => {
    setSelectedDateRange(range);
    
    const now = new Date();
    let startDate: Date;
    
    switch (range) {
      case '7d':
        startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
        break;
      case '30d':
        startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
        break;
      case '90d':
        startDate = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
        break;
      case '1y':
        startDate = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);
        break;
      default:
        startDate = new Date(0); // All time
    }
    
    if (range !== 'all') {
      setFilters({
        ...filters,
        dateRange: {
          start: startDate,
          end: now
        }
      });
    } else {
      const { dateRange, ...restFilters } = filters;
      setFilters(restFilters);
    }
  };
  
  const handleExport = async (format: ExportFormat) => {
    if (!chartContainerRef.current) return;
    
    setIsExporting(true);
    
    try {
      const element = document.querySelector('.chart-dashboard') as HTMLElement;
      if (!element) {
        throw new Error('Chart dashboard not found');
      }
      
      let dataUrl: string;
      
      if (format === 'png') {
        dataUrl = await toPng(element, {
          quality: 1.0,
          backgroundColor: themes[currentTheme].colors.background,
          width: element.scrollWidth,
          height: element.scrollHeight
        });
      } else if (format === 'svg') {
        dataUrl = await toSvg(element, {
          backgroundColor: themes[currentTheme].colors.background,
          width: element.scrollWidth,
          height: element.scrollHeight
        });
      } else {
        // For PDF, we'll use PNG and let the browser handle it
        dataUrl = await toPng(element, {
          quality: 1.0,
          backgroundColor: themes[currentTheme].colors.background,
          width: element.scrollWidth,
          height: element.scrollHeight
        });
      }
      
      // Create download link
      const link = document.createElement('a');
      link.download = `diary-dashboard-${new Date().toISOString().split('T')[0]}.${format}`;
      link.href = dataUrl;
      link.click();
      
    } catch (error) {
      console.error('Export failed:', error);
      alert('Export failed. Please try again.');
    } finally {
      setIsExporting(false);
    }
  };
  
  const toggleFullscreen = () => {
    if (!isFullscreen) {
      // Enter fullscreen
      const element = document.querySelector('.chart-dashboard') as HTMLElement;
      if (element) {
        if (element.requestFullscreen) {
          element.requestFullscreen();
        }
        setIsFullscreen(true);
      }
    } else {
      // Exit fullscreen
      if (document.exitFullscreen) {
        document.exitFullscreen();
      }
      setIsFullscreen(false);
    }
  };
  
  // Load saved theme on component mount
  React.useEffect(() => {
    const savedTheme = localStorage.getItem('chart-theme') as ChartTheme;
    if (savedTheme && themes[savedTheme]) {
      handleThemeChange(savedTheme);
    }
  }, []);
  
  return (
    <div className={`relative ${className}`}>
      {/* Customization Toggle Button */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="fixed top-4 right-4 z-50 bg-white shadow-lg rounded-full p-3 border border-warm-gray-200 hover:bg-warm-gray-50 transition-colors"
        title="Chart Customization"
      >
        <Settings className="w-5 h-5 text-warm-gray-600" />
      </button>
      
      {/* Customization Panel */}
      {isOpen && (
        <div className="fixed top-16 right-4 z-50 bg-white rounded-lg shadow-xl border border-warm-gray-200 p-6 w-80 max-h-96 overflow-y-auto">
          <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-semibold text-warm-gray-800">
                Chart Settings
              </h3>
              <button
                onClick={() => setIsOpen(false)}
                className="text-warm-gray-400 hover:text-warm-gray-600"
              >
                ×
              </button>
            </div>
            
            {/* Theme Selection */}
            <div>
              <label className="block text-sm font-medium text-warm-gray-700 mb-3">
                <Palette className="w-4 h-4 inline mr-2" />
                Theme
              </label>
              <div className="grid grid-cols-2 gap-2">
                {Object.entries(themes).map(([key, theme]) => (
                  <button
                    key={key}
                    onClick={() => handleThemeChange(key as ChartTheme)}
                    className={`p-3 rounded-lg border text-sm font-medium transition-colors ${
                      currentTheme === key
                        ? 'border-blue-500 bg-blue-50 text-blue-700'
                        : 'border-warm-gray-200 hover:border-warm-gray-300 text-warm-gray-700'
                    }`}
                  >
                    <div className="flex items-center gap-2">
                      <div 
                        className="w-3 h-3 rounded-full" 
                        style={{ backgroundColor: theme.colors.primary }}
                      />
                      {theme.name}
                    </div>
                  </button>
                ))}
              </div>
            </div>
            
            {/* Date Range Selection */}
            <div>
              <label className="block text-sm font-medium text-warm-gray-700 mb-3">
                <Calendar className="w-4 h-4 inline mr-2" />
                Date Range
              </label>
              <select
                value={selectedDateRange}
                onChange={(e) => handleDateRangeChange(e.target.value as DateRange)}
                className="w-full p-2 border border-warm-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="7d">Last 7 days</option>
                <option value="30d">Last 30 days</option>
                <option value="90d">Last 90 days</option>
                <option value="1y">Last year</option>
                <option value="all">All time</option>
              </select>
            </div>
            
            {/* Export Options */}
            <div>
              <label className="block text-sm font-medium text-warm-gray-700 mb-3">
                <Download className="w-4 h-4 inline mr-2" />
                Export Charts
              </label>
              <div className="grid grid-cols-3 gap-2">
                <button
                  onClick={() => handleExport('png')}
                  disabled={isExporting}
                  className="p-2 text-xs font-medium border border-warm-gray-300 rounded-lg hover:bg-warm-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  PNG
                </button>
                <button
                  onClick={() => handleExport('svg')}
                  disabled={isExporting}
                  className="p-2 text-xs font-medium border border-warm-gray-300 rounded-lg hover:bg-warm-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  SVG
                </button>
                <button
                  onClick={() => handleExport('pdf')}
                  disabled={isExporting}
                  className="p-2 text-xs font-medium border border-warm-gray-300 rounded-lg hover:bg-warm-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  PDF
                </button>
              </div>
              {isExporting && (
                <p className="text-xs text-warm-gray-500 mt-2">
                  Exporting... Please wait.
                </p>
              )}
            </div>
            
            {/* Fullscreen Toggle */}
            <div>
              <button
                onClick={toggleFullscreen}
                className="w-full flex items-center justify-center gap-2 p-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                {isFullscreen ? (
                  <><Minimize2 className="w-4 h-4" /> Exit Fullscreen</>
                ) : (
                  <><Maximize2 className="w-4 h-4" /> Fullscreen View</>
                )}
              </button>
            </div>
            
            {/* Clear Filters */}
            <div>
              <button
                onClick={clearFilters}
                className="w-full p-3 border border-warm-gray-300 text-warm-gray-700 rounded-lg hover:bg-warm-gray-50 transition-colors"
              >
                Clear All Filters
              </button>
            </div>
          </div>
        </div>
      )}
      
      {/* Fullscreen Overlay */}
      {isFullscreen && (
        <div className="fixed inset-0 z-40 bg-black bg-opacity-50" onClick={toggleFullscreen} />
      )}
    </div>
  );
};

export default ChartCustomization;